package com.chidopi.market.bookstore.actions;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chidopi.cdf.exception.CdfException;
import com.chidopi.cdf.service.IBaseService;
import com.chidopi.cdf.struts1actions.StandardOperatorAction;
import com.chidopi.cdf.util.ModelContextFactory;
import com.chidopi.market.bookstore.domain.Book2City;
import com.chidopi.market.bookstore.domain.BookCategories;
import com.chidopi.market.bookstore.domain.BookCities;
import com.chidopi.market.bookstore.domain.BookItems;
import com.chidopi.market.bookstore.domain.City2Category;
import com.chidopi.market.bookstore.domain.ContextProvider;
import com.chidopi.market.bookstore.service.IBookItemsService;
import com.chidopi.market.util.MessageHandler;

public class BookCityAction extends StandardOperatorAction<BookCities>{
	
	private static Logger logger = LoggerFactory.getLogger(BookCityAction.class);
	
	private IBaseService<BookCities> baseService;
	
	private IBaseService<ContextProvider> cpService;
	
	private IBaseService<BookCategories> categriesService;
	
	private IBookItemsService bookItemsService;
	
	public BookCityAction(){
		this("");
	}
	
	@SuppressWarnings("unchecked")
	public BookCityAction(String entryURL) {
		this.entryURL = entryURL;
		try {
			this.baseService = (IBaseService<BookCities>)
				ModelContextFactory.get("bookCitiesService", IBaseService.class);			
		} catch (Exception e) {
			this.baseService = null;
			logger.warn("initial", e);
		}
		
		try {
			this.cpService = (IBaseService<ContextProvider>)
				ModelContextFactory.get("contextProviderService", IBaseService.class);			
		} catch (Exception e) {
			this.baseService = null;
			logger.warn("initial", e);
		}
		
		try {
			this.categriesService = (IBaseService<BookCategories>)
				ModelContextFactory.get("bookCategoriesService", IBaseService.class);			
		} catch (Exception e) {
			this.baseService = null;
			logger.warn("initial", e);
		}
		
		try {
			this.bookItemsService = (IBookItemsService)
				ModelContextFactory.get("bookItemsService", IBaseService.class);			
		} catch (Exception e) {
			this.baseService = null;
			logger.warn("initial", e);
		}
		
	}
	
	public ActionForward init(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("vo", null);
		dynaForm.set("op", null);
		
		// ContextProviders
		List<ContextProvider> list = cpService.find(null);		
		dynaForm.set("contextProviders", list);
		logger.info("contextProviders:" + list);
		return mapping.findForward("success");
	}
	
	public ActionForward back(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("success");
	}
	
	private static final String[] conditions = {"id", "cityname", "cp_id" , "enable_flag"};
	public ActionForward query(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (null == this.baseService) return mapping.findForward("error");
		StringBuffer sql = new StringBuffer();
		ArrayList<String> args = new ArrayList<String>();
		for (String cond : conditions) {
			String value = (String) request.getParameter(cond);
			if (value == null || value.trim().equals("")) continue;
			logger.debug(cond + "=" + value);

			if(cond.endsWith("_flag") && request.getParameterValues(cond).length >1){
				 continue;
			}
			
			if (sql.length() > 1) sql.append("and ");
			if(cond.endsWith("_flag") || cond.equals("cp_id") ){
				sql.append(cond + " = ? ");
				args.add( value );
			}else if(cond.equals("id")){
				sql.append("a.id like ? ");
				args.add("%" + value +"%");
			}else {
				sql.append(cond + " like ?");
				args.add("%" + value +"%");
			}
		}
		
		logger.debug("sql=" + sql.toString());
		List<BookCities> list = this.baseService.find(sql.toString(),args.toArray());
		logger.debug("size=" + list.size());
		JSONArray json = JSONArray.fromObject(list);

		PrintWriter out=response.getWriter();
		logger.debug(json.toString());
        out.println(json);
        out.flush();
		return null;
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		logger.debug("id=" + id);
		BookCities t = this.baseService.findById(new Integer(id));
		if (null == t) {
			logger.warn("ContextProvider[id={}] is deleted!!", id);
			return mapping.findForward("err");
		}
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "delete");
		dynaForm.set("vo", t);
		// ContextProviders
		List<ContextProvider> list = cpService.find(null);		
		dynaForm.set("contextProviders", list);
		
		// bookCategries 
		List<BookCategories> categories = this.categriesService.find(null);
		dynaForm.set("bookCategories", categories);
		
		// bookItems
		List<BookItems> books = this.bookItemsService.find(" enable_flag = 'Y' ");
		dynaForm.set("bookItems", books);
		
		return mapping.findForward("success");
	}

	public ActionForward insert(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		logger.debug("id=" + id);
		BookCities t = this.baseService.findById(id);
		if (null == t) t = new BookCities();
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "insert");
		dynaForm.set("vo", t);
		// ContextProviders
		List<ContextProvider> list = cpService.find(null);		
		dynaForm.set("contextProviders", list);
		
		// bookCategries 
		List<BookCategories> categories = this.categriesService.find(null);
		dynaForm.set("bookCategories", categories);
		
		// bookItems
		List<BookItems> books = this.bookItemsService.find(" enable_flag = 'Y' ");
		dynaForm.set("bookItems", books);
		
		return mapping.findForward("success");
	}

	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		logger.debug("id=" + id);
		BookCities t = this.baseService.findById(id);
		if (null == t) {
			logger.warn("BookItems[id={}] is deleted!!", id);
			return mapping.findForward("err");
		}
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "update");
		dynaForm.set("vo", t);
		
		// ContextProviders
		List<ContextProvider> list = cpService.find(null);		
		dynaForm.set("contextProviders", list);
		
		// bookCategries 
		List<BookCategories> categories = this.categriesService.find(null);
		dynaForm.set("bookCategories", categories);
		
		// bookItems
		List<BookItems> books = this.bookItemsService.find(" enable_flag = 'Y' ");
		dynaForm.set("bookItems", books);
				
		return mapping.findForward("success");
	}

	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String op = request.getParameter("op");
		Integer userId = (Integer) request.getSession().getAttribute("user_id");
		logger.debug("op=" + op);
		BookCities t = new BookCities();
		try {
			DynaBean dynaForm = (DynaBean) form;
			PropertyUtils.copyProperties(t, dynaForm.get("vo"));
			logger.debug(t.getId() + ":" + t.getCityname() + "/" + t.getCp().getId());
		} catch (Exception e) {
			logger.warn("PropertyUtils", e);
			return mapping.findForward("err");
		}
		
		// City2Categorys Settings
		// format: CATEGORY_ID,PARENT_ID,LEVEL,ENABLE_FLAG
		String [] categories = request.getParameterValues("categories");
		List<City2Category> ccList = new ArrayList<City2Category>();	
		if(categories != null && categories.length > 0){				
			for(String string : categories){
			    logger.debug("categorty: " + string);
			    String [] values = string.split(";");
			    City2Category cc =  new City2Category(values);		    
			    ccList.add(cc);
			}			
		}
		t.setCategories(ccList);
		// Book2City settings
		//BOOK_ID, SALE_PRICE, SUBSCRIBE_QUOTA, ENABLE_FLAG
		String [] books = request.getParameterValues("books");
		List<Book2City> bcList= new ArrayList<Book2City>();
		if(null != books && books.length > 0){		
			for(String book: books){
				logger.debug("book: " + book);
				String [] values = book.split(";");
				Book2City bc = new Book2City(values);
				bcList.add(bc);
			}		
		}
		t.setBooks(bcList);
		
		int ret = -1;
		if ("insert".equals(op)) {
			t.setCreate_by(userId);
			ret = this.baseService.insert(t);
		} else if ("update".equals(op)) {
			t.setUpdate_by(userId);
			ret = this.baseService.update(t);
		} else if ("delete".equals(op)) {
			t.setUpdate_by(userId);
			try{
				ret = this.baseService.delete(t);
			}catch(CdfException cex){
				MessageHandler.getInstance().processError(request, cex.getMessage());
			}			
		}
		if (ret > -1) {
			request.setAttribute("entryURL", entryURL);
			return mapping.findForward("success");
		}else {
			return mapping.findForward("err");
		}
	}

}
